package com.leetcode.problems071;

import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/simplify-path/
 * @Date 2021/12/09 14:34
 * @Author ghery
 * @Version V1.0
 */
public class Solution {

    public String simplifyPath(String path) {
        if(path == null || path.length() == 0){
            return path;
        }
        String[] pathArr = path.split("/");
        Stack<String> stack = new Stack<>();
        stack.push("/");
        for (String s : pathArr) {
            if(s.length() == 0 || s.equals(".")){
                continue;
            }
            if(stack.isEmpty() || !s.equals("..")){
                stack.push(s);
            }else if(stack.peek().equals("/")){
                //啥也不做
            }else{
                stack.pop();
            }
        }
        StringBuilder ans = new StringBuilder();
        while (!stack.isEmpty()){
            String item = stack.pop();
            if(!item.equals("/")){
                ans.insert(0,item);
                ans.insert(0,"/");
            }
        }
        if(ans.length() == 0){
            return "/";
        }
        return ans.toString();
    }



    public static void main(String[] args) {
        String paht = "/a/./b/../../c/";
        System.out.println(new Solution().simplifyPath(paht));
    }
}
